/* tool to read power production data for SMA solar power convertors
   Copyright flonatel GmbH & Co. KG, 2012

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "timestamp.h"
#include <stdlib.h>
#include <sys/time.h>

timestamp_p time_stamp_constructor()
{
	timestamp_p rval = malloc(sizeof(timestamp_t));
	timestamp_set_current_time(rval);
	return rval;
}

void timestamp_destuctor(timestamp_p self)
{
	free(self);
}

void timestamp_set_current_time(timestamp_p self)
{
	gettimeofday(&self->tv, 0);
}

void timestamp_duration_since(timestamp_p ts)
{
	timestamp_p now = time_stamp_constructor();
	struct timeval result;
	timersub(&now->tv, &ts->tv, &result);
	ts->tv = result;
	timestamp_destuctor(now);
}

double timestamp_as_double(timestamp_p self)
{
	return (double)self->tv.tv_sec
			+ (double)self->tv.tv_usec / 1000000.0;
}
